package rudia.org.auth.service;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import rudia.net.daumsearch.dao.MainDao;
import rudia.org.core.Rudia;

@Service
public class AuthService {

	@Autowired
	private MainDao mainDao;

	public void list() throws InterruptedException {
		HashMap map = new HashMap();

		map.put("aa", "key");
//		 map.put("aa", "key" + new Date().toString());
		map.put("bb", "fff2" + new Date().toString());

//		mainDao.insert(map);

		List<HashMap<String, String>> outputs = mainDao.select(map);

		for (int i = 0; i < outputs.size(); i++) {
			HashMap aa = (HashMap) outputs.get(i);
			Rudia.log.info(aa.get("aa"));
			Rudia.log.info(aa.get("bb"));
			Thread.sleep(1000);
		}
	}

	public void callDaumMap(String qry) throws Exception {

		/* TEST */
//		 int minx = 475640;
//		 int miny = 1093600;
//		
//		 int maxx = 525640;
//		 int maxy = 1143600;

		/* 전국 */
//		int minx = -74360;
//		int miny = -506400;
//
//		int maxx = 1452680;
//		int maxy = 1763040;
		
		/* 전국 */
		int minx = -74360;
		int miny = -106400;
		
		int maxx = 1452680;
		int maxy = 1763040;

		int oneblk = 15000;// 블럭사이즈
		double oneblkCnt = 0;// 한블럭안의 갯수
		double pageSize = 15; // 한페이지 사이즈
		int pageMax = 2;// j순환문의 최고 값 바인딩
		int place_totalcount = 0;

		int tot_cnt = 0;// insert총 수
		int i = 0, j = 0, curx = 0, cury = 0;

		try {

			for (cury = miny; cury < maxy + oneblk; cury += oneblk) {
				for (curx = minx; curx < maxx + oneblk; curx += oneblk) {

					for (j = 1; j < pageMax; j++) {// Page 반복문
						try {

							JSONObject jObject = this.getDaumMapGet(qry, j, curx, cury, curx + oneblk, cury + oneblk);
							place_totalcount = jObject.getInt("place_totalcount");

							if (place_totalcount > 0) {

								JSONArray dataArray = jObject.getJSONArray("place");
								oneblkCnt = jObject.getDouble("page_count");
								pageMax = (int) (Math.ceil(oneblkCnt / pageSize) + 1);

								/* Json Object */
								try {
									for (i = 0; i < dataArray.length(); i++) {// insert
										JSONObject jsonobj = dataArray.getJSONObject(i);
										jsonobj.put("seq", curx + "_" + cury + "_" + j + "_" + i);
										jsonobj.put("qry", jObject.get("org_query"));
										jsonobj.put("page", jObject.get("page") + "");
										jsonobj.put("catelink", jObject.get("cateLink"));
										jsonobj.put("place_totalcount", jObject.get("place_totalcount") + "");

										HashMap hm = (HashMap) toMap(jsonobj);
										mainDao.insertShop(hm);

									}// end for i

								} catch (Exception e) {
									Rudia.log.info("Error ★건(" + i + ") For :" + e);
								}
								tot_cnt += dataArray.length();
								Rudia.log.info("oneblkCnt/place_totalcount: " + oneblkCnt + "/" + place_totalcount + "  |  page/pageMax: " + j + "/" + pageMax + "  |  cnt: " + dataArray.length() + " ...ing!! tot_cnt: " + tot_cnt);
							} else {
								Rudia.log.info("oneblkCnt: " + 0 + " ...ing!!");

							}
						} catch (Exception e) {
							Rudia.log.info("Error Page(" + j + ") For :" + e);
						}
						Thread.sleep(350);

					}// end for j
					Rudia.log.info("curx: " + curx + "~" + (curx + oneblk) + " / " + maxx + "  |  cury: " + cury + "~" + (cury + oneblk) + " / " + maxy + " ..ing!! tot_cnt: " + tot_cnt);
				}// end curx

			}// end cury
		} catch (Exception e) {
			Rudia.log.info("curx: " + curx + "~" + (curx + oneblk) + " / " + maxx + "  |  cury: " + cury + "~" + (cury + oneblk) + " / " + maxy + "  |  Page : " + j + "_" + i + " Error!!");
			Rudia.log.info(e);
		}
		Rudia.log.info("curx: " + curx + "~" + (curx + oneblk) + " / " + maxx + "  |  cury: " + cury + "~" + (cury + oneblk) + " / " + maxy + "  |  Page : " + j + "_" + i + " End!!! tot_cnt: " + tot_cnt);

	}

	public Map toMap(JSONObject object) throws JSONException {
		Map<String, Object> map = new HashMap<String, Object>();

		Iterator<String> keysItr = object.keys();
		while (keysItr.hasNext()) {
			String key = keysItr.next();
			Object value = object.get(key);

			map.put(key, value);
		}
		return map;
	}

	private JSONObject getDaumMapGet(String qry, int page, int minx, int miny, int maxx, int maxy) throws Exception {
		String url = "http://map.search.daum.net/mapsearch/map.daum";
		// url = url + "?callback=aaa&q=" + URLEncoder.encode(qry, "UTF-8") +
		// "&msFlag=S&mcheck=Y&rect=-1052280%2C-523760%2C409480%2C1787920&page="
		// + page + "&sort=0";
		// &rect=-484920,-508080,2561480,1729360
		url = url + "?callback=aaa&q=" + URLEncoder.encode(qry, "UTF-8") + "&msFlag=S&mcheck=Y&rect=" + minx + "," + miny + "," + maxx + "," + maxy + "&page=" + page + "&sort=0";

		// add header
		HttpGet request = new HttpGet(url);
		request.setHeader("Accept", "*/*");
		request.setHeader("Accept-Encoding", "gzip, deflate, sdch");
		request.setHeader("Accept-Language", "ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4");
		request.setHeader("User-Agent", "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19");//
		request.setHeader("Referer", "http://map.daum.net/");// d
		request.setHeader("Connection", "keep-alive");
		request.setHeader("Host", "map.search.daum.net");
		request.setHeader("Content-Type", "text/plain;charset=UTF-8");
		request.setHeader("Cookie", "TIARA=QG-BtlPlESLIrMf-hHm1nWZnJuiCD1I3kQYJsHcmsveG5lIjhfS3uRAsyYDNrqIFx-IL_NE2Y8oGXvKzFJ5RtShdvz_Kz5FH");

		HttpClient client = HttpClientBuilder.create().build();
		HttpResponse response = client.execute(request);
		int responseCode = response.getStatusLine().getStatusCode();
		Rudia.log.debug("*** responseCode = " + responseCode);
		HttpEntity entity = response.getEntity();
		String content = EntityUtils.toString(entity);
		content = content.substring(5, content.length() - 2);/* "aaa ({...})" */

		content = content.replaceAll("\\\\", "");

		return new JSONObject(content);

	}

}